package cache

import (
	"fmt"
	"time"
)

type RedisMarker struct {
	client     *RedisClient
	key        string
	expiration time.Duration
}

func CreateRedisMarker(client *RedisClient, key string, args ...interface{}) *RedisMarker {
	if len(args) > 0 {
		key = fmt.Sprintf(key, args...)
	}

	return &RedisMarker{client: client, key: key}
}

func (marker *RedisMarker) Key() string {
	return marker.key
}

func (marker *RedisMarker) GetExpiration() time.Duration {
	return marker.expiration
}

func (marker *RedisMarker) SetExpiration(expiration time.Duration) *RedisMarker {
	if expiration < 0 {
		expiration = 0
	}
	marker.expiration = expiration
	return marker
}

func (marker *RedisMarker) Expire(duration time.Duration) error {
	return marker.client.Client.Expire(marker.key, duration).Err()
}

func (marker *RedisMarker) ExpireAt(t time.Time) error {
	return marker.client.Client.ExpireAt(marker.key, t).Err()
}

func (marker *RedisMarker) Mark() (bool, error) {
	return marker.client.Client.SetNX(marker.key, 1, marker.expiration).Result()
}

func (marker *RedisMarker) Unmark() (bool, error) {
	if n, err := marker.client.Client.Del(marker.key).Result(); err != nil {
		return false, err
	} else {
		return n == 1, nil
	}
}

func (marker *RedisMarker) Exist() (bool, error) {
	if exist, err := marker.client.Client.Exists(marker.key).Result(); err != nil {
		return false, err
	} else {
		return 1 == exist, nil
	}
}
